// 行内样式 px 转成 rem
const loaderUtils = require('loader-utils')
// 默认参数
let defaultsProp = {
  rootValue: 16,
  unitPrecision: 5,
  minPixelValue: 1
}
const template = /<template>([\s\S]+)<\/template>/gi
// const checkContent = /(\d+)\s*px(?![\w-]*[\s\])-])/g;
const checkContent = /(\d+)\s*px(?![\w-]*\s*])/g;
const checkStyle = /style="[^"]*"/g;

module.exports = function (source) {
  const opts = loaderUtils.getOptions(this)
  const defaults = Object.assign({}, defaultsProp, opts)
  let _source = ''
  if (template.test(source)) {
    _source = source.match(template)[0]
  }
  let pxGlobalRegExp = new RegExp(checkContent.source, 'ig')
  if (pxGlobalRegExp.test(_source)) {
    let $_source = source.replace(checkStyle, function(match) {
      return match.replace(pxGlobalRegExp, createPxReplace(defaults.rootValue, defaults.unitPrecision, defaults.minPixelValue))
    });
    return source.replace(template, $_source)
  } else {
    return source
  }
}
function createPxReplace(rootValue, unitPrecision, minPixelValue) {
  return (m, $1) => {
    if (!$1) return m;
    const pixels = parseFloat($1);
    if (pixels < minPixelValue) return m;
    const fixedVal = toFixed(pixels / rootValue, unitPrecision);
    return fixedVal === 0 ? "0" : fixedVal + "rem";
  };
}

function toFixed(number, precision) {
  const multiplier = Math.pow(10, precision + 1),
    wholeNumber = Math.floor(number * multiplier);
  return (Math.round(wholeNumber / 10) * 10) / multiplier;
}
